package com.collabscm.waf.solution.validation;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.metadata.BeanDescriptor;

import com.collabscm.waf.solution.profiler.Monitor;

/**
 * JSR 303的工具类，提供对整体平台的验证
 *
 * @author Zeng Raoxing
 */
public class BeanValidationUtils {
	
	private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

	public static BeanDescriptor getConstraintsForClass(Class<?> clazz) {
		return validator.getConstraintsForClass(clazz);
	}

	public static <T> T unwrap(Class<T> type) {
		return validator.unwrap(type);
	}

	/**
	 * 验证Bean，默认直接抛出BeanValidationFailure。
	 * 
	 * @param <T>
	 * @param object
	 * @param groups
	 */
	public static <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) {
		return validate(true, object, groups);
	}
	
	@Monitor(uptime=10)
	public static <T> Set<ConstraintViolation<T>> validate(boolean throwFailure, T object, Class<?>... groups) {
		Set<ConstraintViolation<T>> constraints = validator.validate(object, groups);
		if(throwFailure && constraints.size() > 0) {
			//如果有错误，那么就抛出验证错误。
			throw new BeanValidationFailure(object.getClass(), constraints);
		}
		return constraints;
	}

	public static <T> Set<ConstraintViolation<T>> validateProperty(T object, String propertyName, Class<?>... groups) {
		return validator.validateProperty(object, propertyName, groups);
	}

	public static <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value,
			Class<?>... groups) {
		return validator.validateValue(beanType, propertyName, value, groups);
	}
	
}
